<template>
    <div>
        <div class="e-table" style="background-color: #fff">
            <div class="top">
                <div class="left">
                    <div class="select_box">
                        <el-button size="small" class="btn-greenYellow" @click="importList"
                            :disabled="!contractId"
                        >引入清单</el-button>
                        <span class="label">查看清单范围：</span>
                        <el-radio-group v-model="qingdanRange">
                            <el-radio label="1">本期结算清单</el-radio>
                            <el-radio label="all">全部清单</el-radio>
                        </el-radio-group>
                        <span class="label">查看清单维度：</span>
                        <el-radio-group v-model="qingdanRange">
                            <el-radio label="1">细目—>结构部位</el-radio>
                            <el-radio label="2">结构部位—>细目</el-radio>
                        </el-radio-group>
                        <span class="label">期数：</span>
                        <div style="flex: 1;">
                            <el-select v-model="qishu" multiple collapse-tags placeholder="请选择" @change="onSelectQishu">
                                <el-option
                                    v-for="item in qishuOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </div>
                    </div>
                </div>
                <div class="right">
                    <div>
                        <el-input
                            placeholder="请输入细目编号、细目名称或结构部位进行搜索"
                            size="small"
                            v-model="searchKey"
                            @blur="onSearch"
                        >
                            <img src="@/assets/search.png" slot="suffix" @click="onSearch" />
                        </el-input>
                    </div>
                </div>
            </div>
            <!-- 表格 -->
            <div class="e-tree-table">
                <div class="errorMsg" v-if="errorMsg.length>0">
                    <span >
                        {{ errorMsg.join(',') }}
                    </span>
                </div>
                <el-table v-show="!isSearch"
                    ref="tableRef"
                    key="tableRef"
                    border
                    style="width: 100%"
                    max-height="300"
                    row-key="uuid"
                    :data="tableList"
                    :tree-props="{
                        children: 'children',
                        hasChildren: 'hasChildren'
                    }"
                    :load="onload"
                    lazy
                    class="table"
                >
                    <el-table-column fixed label="操作" width="150">
                        <template slot-scope="{ row,$index }">
                            <div class="handle">
                                <img src="@/assets/btn/delete.png"  @click="handleDeletePlanList(row,$index)">
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="itemNo" label="细目编号" min-width="200" align="left"></el-table-column>
                    <el-table-column prop="itemName" label="细目名称" min-width="220"></el-table-column>
                    <el-table-column prop="structureName" label="结构部位" min-width="200" align="left">
                        <template slot-scope="{ row }">
                            <div>{{ row.structureName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unit" align="center" label="单位" width="120"></el-table-column>
                    <el-table-column prop="contractQuantity"  align="center"  label="合同数量" width="120">
                        <template slot-scope="{ row }">
                            <div>{{ row.contractQuantity }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="contractPrice" align="center" label="合同单价" width="120"></el-table-column>
                    <el-table-column prop="contractAmount"  align="center"  label="合同金额(元)" width="150"></el-table-column>
                    <el-table-column prop="settlementQuantity" label="本期结算数量"  align="right"  width="200">
                        <!-- 清单最子级 单位是 m³ 最子级带入后修改 -->
                        <template slot-scope="{ row }">
                            <!-- 修改后计算 本期结算金额 -->
                            <div style="display: flex; align-items: center;" v-if="row.type === 1 && row.isDetailed === 1 && row.unit === 'm³'">
                                <el-input
                                    v-model.number="row.settlementQuantity"
                                    placeholder="请输入本期结算数量"
                                    @change="quantityChange(row)"
                                ></el-input>
                                <historyUpdateTable
                                    :typeVal="typeVal"
                                    @clickIcon="clickIcon([])"
                                    :historyTable="historyTableData"
                                />
                            </div>
                            <div v-else>{{ row.settlementQuantity }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="settlementAmount" label="本期结算金额(元)"  align="right"  width="200">
                        <!-- 清单最子级 单位是 总额 则填写 -->
                        <template slot-scope="{ row }">
                            <!-- 修改后向上汇总 -->
                            <div style="display: flex; align-items: center;" v-if="row.type === 1 && row.isDetailed === 1 && row.unit === '总额'">
                                <el-input
                                    v-model.number="row.settlementAmount"
                                    placeholder="请输入本期结算金额"
                                    @change="quantityChange(row)"
                                ></el-input>
                                <historyUpdateTable
                                    :typeVal="typeVal"
                                    @clickIcon="clickIcon([])"
                                    :historyTable="historyTableData"
                                />
                            </div>
                            <!-- 保证金 扣-xx保证金 填写 -->
                            <div v-if="row.type === 1 && row.isDetailed === 4">
                                <!-- 修改后计算 本期结算数量 -->
                                <el-input
                                    v-model.number="row.settlementAmount"
                                    placeholder="请输入本期结算金额"
                                    @change="quantityChange(row)"
                                ></el-input>
                                <historyUpdateTable
                                    :typeVal="typeVal"
                                    @clickIcon="clickIcon([])"
                                    :historyTable="historyTableData"
                                />
                            </div>
                            <div v-else>
                                {{ row.settlementAmount }}
                            </div>
                        </template>
                    </el-table-column>
                    <!-- 此处循环 tps -->
                    <el-table-column align="right" width="180"
                        v-for="item in columnArr" :key="item.id"
                        :prop="item.prop"
                        :label="item.label"
                    >
                        <template slot-scope="{ row }">
                            <div>{{ row.unitPrice }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="upQuantity" label="截止上期末累计结算数量" align="right" width="180">
                        <template slot-scope="{ row }">
                            <!-- 第1期到第n期数量汇总 -->
                            <div>{{ row.upQuantity }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="upAmount" label="截止上期末累计结算金额(元)" align="right" width="220">
                        <template slot-scope="{ row }">
                            <!-- 第1期到第n期金额汇总 -->
                            <div>{{ row.upAmount }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="currentTotalSettlementQuantity" label="截止本期末累计结算数量" align="right" width="180">
                        <template slot-scope="{ row }">
                            <div>{{ row.currentTotalSettlementQuantity }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="currentTotalSettlementAmount" label="截止本期末累计结算金额(元)" align="right" width="220">
                        <template slot-scope="{ row }">
                            <div>{{ row.currentTotalSettlementAmount }}</div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
    </div>
</template>
<script>
import { uidBuilder } from '@/api/base/uid'
// eslint-disable-next-line no-unused-vars
import { selectDataClient, showLoading, hideLoading, getUuid, getItemOfTreeArr, openAppClient } from '@/utils/common'
import { getDetail } from '@/api/settlementManagement/gongchengjieshuan/guochengjieshuan'
import { mapMutations } from 'vuex'
import historyUpdateTable from './historyUpdateTable'
export default {
    props: {
        billId: {
            type: String,
            default: ''
        },
        contractId: {
            type: String,
            default: ''
        },
        qishuOptions: {
            type: Array,
            default () {
                return [{
                    label: '全部',
                    value: 0,
                }, {
                    label: '第1期',
                    value: 1,
                }, {
                    label: '第2期',
                    value: 2,
                }]
            }
        },
        tableData: {
            type: Array,
            default: function () {
                return []
            }
        },
        errorMsg: { //表格错误提示
            type: Array,
            default: function () {
                return []
            }
        },
        //是否可以编辑
        isEdit: {
            default: true
        },
    },
    model: {
        prop: 'tableData',
        event: 'change'
    },
    components: {
        historyUpdateTable,
    },
    computed: {
        //截止本期末变更后数量
        quantityEndChange () {
            return row=>{
                const quantityEndChange = row.quantityEndChange
                row.quantityEndChange = parseFloat(row.quantityAfterChange ? row.quantityAfterChange : 0) + parseFloat(row.quantity ? row.quantity : 0)
                if(quantityEndChange != row.quantityEndChange && row.quantityEndChange != row.quantity) {
                    this.onCalcAmount(row)
                }
                return row.quantityEndChange
            }
        },
        //截止本期末变更后单价
        unitPriceEndChange () {
            return row=>{
                const unitPriceEndChange = row.quantityEndChange
                row.unitPriceEndChange = parseFloat(row.unitPriceAfterChange ? row.unitPriceAfterChange : 0) + parseFloat(row.unitPrice ? row.unitPrice : 0)
                if(unitPriceEndChange != row.unitPriceEndChange && row.unitPriceEndChange != row.unitPrice ) {
                    this.onCalcAmount(row)
                }
                return row.unitPriceEndChange
            }
        },
    },
    data () {
        return {
            typeVal: 'amount',
            detailsOfProposedArr: [],
            mapTableData: {},
            addList: [], // 缓存新增数据
            unitList: [],
            searchKey: '',
            isSearch: false,
            materialList: [],
            showTable: true,
            historyTableData: [],
            qingdanRange: '1',
            qishu: [0, 1, 2],
            oldQishu: [0, 1, 2],
            columnArr: [], //表格展示期数数组
            oldcolumnArr: [], //表格保存期数数据数组
            tableList: [] //表格整体数组
        }
    },
    mounted () {
        // 获取父组件传递过来的数据
        this.tableList = this.tableData
        this.columnArr = [{
            id: 1,
            prop: 'settlementQuantity1',
            label: '第1期结算数量'
        }, {
            id: 2,
            prop: 'settlementAmount1',
            label: '第1期结算金额'
        }, {
            id: 3,
            prop: 'settlementQuantity2',
            label: '第2期结算数量'
        }, {
            id: 4,
            prop: 'settlementAmount2',
            label: '第2期结算金额'
        }]
        this.oldcolumnArr = [{
            id: 1,
            prop: 'settlementQuantity1',
            label: '第1期结算数量'
        }, {
            id: 2,
            prop: 'settlementAmount1',
            label: '第1期结算金额'
        }, {
            id: 3,
            prop: 'settlementQuantity2',
            label: '第2期结算数量'
        }, {
            id: 4,
            prop: 'settlementAmount2',
            label: '第2期结算金额'
        }]
    },
    methods: {
        ...mapMutations(
            'contract', ['setMaterialList']
        ),
        ...mapMutations(['setHistoryTableData', 'setSelectedInfo']),
        //删除单条结算明细数据
        handleDeletePlanList (row) {
            let isSwitch = true
            this.acceptanceData.forEach(item=>{
                item.children.forEach((s, i)=>{
                    if(s.dtlId == row.dtlId) {
                        this.clientPop(
                            'info',
                            this.oneDeleteErr,
                            ()=>{
                                //判断此条数据是否为新增
                                if(s.changeType != 1) {
                                    const target = {
                                        dtlId: s.dtlId,
                                        changeType: -1
                                    }
                                    this.deleteDataList.push(target)
                                }
                                item.children.splice(i, 1)
                                //更新页面
                                this.taxAmountEvent(this.formData.taxAmount)
                            }
                        )
                        //找到目标后没有必要继续循环直接退出
                        isSwitch = false
                        return
                    }
                })
                if(!isSwitch) {
                    return
                }
            })
        },
        // 获取数据
        getData () {
            this.showTable = false
        },
        //根据选中期数展示对应列表数据
        selectStageShowColumn () {
            let list = []
            //当数组为中存在0说明是全选
            if(this.qishu.indexOf(0) > -1) {
                list = this.oldcolumnArr
            }else {
                this.qishu.forEach(item=>{
                    this.oldcolumnArr.forEach(old=>{
                        old.prop.indexOf(item) > -1 && list.push(old)
                    })
                })
            }
            this.columnArr = list
        },
        // 引入清单
        importList () {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: 'SelectProjectSettleDetail', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                // InitParamsStr: this.contractId,    // 接口参数(name为模拟参数)
                InitParamsStr: '1534855327300407297',
                Title: '引入清单' // 标题
            }).then(val => {
                // 保存用户选择返回数据到store
                this.setSelectedInfo(val)
                // 客户端弹窗预览结果
                // 参数依次为: 打开页面地址、标题、回调函数
                openAppClient('/showSelectedData', '选择结果')
                const result = val
                // const result = [
                //     {
                //         'ItemName': '桥梁、涵洞',
                //         'Unit': '',
                //         'ItemNo': '400章',
                //         'ListId': '1534855468375797761',
                //         'ParentId': '0',
                //         'Structure': [
                //             {
                //                 'ListId': '1527113207537922049',
                //                 'ParentId': '1527113207537922050',
                //                 'StructureId': '1530116382235934722',
                //                 'StructureName': '扩大基础',
                //                 'StructureNo': '1-1-1',
                //                 'StructureType': 4,
                //                 'TreeTitle': '扩大基础',
                //                 'LoadingState': null,
                //                 'OnLoading': false
                //             }
                //         ],
                //         'LoadingState': null,
                //         'OnLoading': false
                //     },
                //     {
                //         'ItemName': '钢筋',
                //         'Unit': '',
                //         'ItemNo': '403',
                //         'ListId': '1534855469806055426',
                //         'ParentId': '1534855468375797761',
                //         'Structure': [
                //             {
                //                 'ListId': '1527113207537922049',
                //                 'ParentId': '1527113207537922050',
                //                 'StructureId': '1530116382235934722',
                //                 'StructureName': '扩大基础',
                //                 'StructureNo': '1-1-1',
                //                 'StructureType': 4,
                //                 'TreeTitle': '扩大基础',
                //                 'LoadingState': null,
                //                 'OnLoading': false
                //             }
                //         ],
                //         'LoadingState': null,
                //         'OnLoading': false
                //     },
                //     {
                //         'ItemName': '基础钢筋（含灌注桩、承台、柱系梁、沉桩、沉井等）',
                //         'Unit': 'kg',
                //         'ItemNo': '403-1',
                //         'ListId': '1534855470850437121',
                //         'ParentId': '1534855469806055426',
                //         'Structure': [
                //             {
                //                 'ListId': '1527113207537922049',
                //                 'ParentId': '1527113207537922050',
                //                 'StructureId': '1530116382235934722',
                //                 'StructureName': '扩大基础',
                //                 'StructureNo': '1-1-1',
                //                 'StructureType': 4,
                //                 'TreeTitle': '扩大基础',
                //                 'LoadingState': null,
                //                 'OnLoading': false
                //             }
                //         ],
                //         'LoadingState': null,
                //         'OnLoading': false
                //     }
                // ]
                const stack = [] // 保存树节点
                let curItem = result.shift()
                while (curItem) {
                // 拼出表格所需字段
                    curItem = {
                        ListId: curItem.ListId,
                        Structure: curItem.Structure,
                        uuid: getUuid(),
                        'billId': this.billId,
                        'changeType': 0,
                        'contractAmount': 0,
                        'contractPrice': 0,
                        'contractQuantity': 0,
                        'currentTotalSettlementAmount': 0,
                        'currentTotalSettlementQuantity': 0,
                        'dtlId': '',
                        'isBillLevel': 0,
                        'isDetailed': 0,
                        'itemName': curItem.ItemName,
                        'itemNo': curItem.ItemNo,
                        'marginType': 0,
                        'parentId': curItem.ParentId,
                        'settlementAmount': 0,
                        'settlementQuantity': 0,
                        'sourceId': '',
                        'structureId': '',
                        'structureName': '',
                        'thisLevelId': curItem.ListId,
                        'type': 1,
                        'unit': curItem.unit,
                        children: []
                    }
                    // 结构部位放到对应节点的 children 下面
                    curItem.children = curItem.Structure.map(item => ({
                        ListId: curItem.ListId,
                        uuid: getUuid(),
                        'billId': this.billId,
                        'changeType': 0,
                        'contractAmount': 0,
                        'contractPrice': 0,
                        'contractQuantity': 0,
                        'currentTotalSettlementAmount': 0,
                        'currentTotalSettlementQuantity': 0,
                        'dtlId': '',
                        'isBillLevel': 0,
                        'isDetailed': 0,
                        'itemName': item.TreeTitle,
                        'itemNo': item.StructureNo,
                        'marginType': 0,
                        'parentId': item.ParentId,
                        'settlementAmount': 0,
                        'settlementQuantity': 0,
                        'sourceId': '',
                        'structureId': item.StructureId,
                        'structureName': item.StructureName,
                        'thisLevelId': item.ListId,
                        'type': 1,
                        'unit': '',
                    }))
                    // 如果是顶级，则直接入栈
                    if (curItem.parentId === '0') {
                        stack.push(curItem)
                    } else {
                    // 如果不是顶级，在结果树中找对应的父级
                        const treeArr = getItemOfTreeArr(stack, 'ListId', curItem.parentId)
                        const parent = treeArr.pop()
                        if (parent) {
                            if (!parent.children) {
                                parent.children = []
                            }
                            parent.children.push(curItem)
                        }
                    }
                    curItem = result.shift()
                }
                this.tableList = this.tableList.concat(stack)
                this.$emit('change', this.tableList)
            })
        },
        async onload (row, treeNode, resolve) {
            let result
            if(row.children.length > 0) {
                result = row.children
            } else {
                // 如果不是最子级，就从接口取
                if (!row.isDetailed) {
                    result = await getDetail({
                        billId: this.billId,
                        parentId: '0'
                    })
                } else {
                // 是最子级，则初始为空，合并新增数据，并设为非最子级
                    result = []
                    row.isDetailed = false
                }
                // 如果有缓存数据，说明是点击的 “添加子级” 按钮
                if (this.addList.length > 0) {
                    result = result.concat(this.addList)
                    this.addList = []
                }
            }
            row.treeNode = treeNode
            row.resolve = resolve
            row.children = result
            this.mapTableData[row.billId] = row
            resolve(result)
        },
        // 修改数量、金额
        quantityChange (row) {
            const data = this.tableList
            // 在树中找出当前元素的位置 结构
            const stack = getItemOfTreeArr(data, 'uuid', row.uuid)
            // 从父级开始汇总，向上到顶级
            stack.pop() // 当前级出栈
            let parent = stack.pop()
            while (parent) {
                parent.settlementQuantity = parent.children.reduce((count, prev) => count + Number(prev.settlementQuantity), 0)
                parent = stack.pop()
            }
        },
        // 查看修改历史
        clickIcon (list) {
            // this.typeVal = 'num'
            this.setHistoryTableData(list || [])
        },
        // 修改期数
        onSelectQishu (e) {
            let difference
            // 选中
            if (e.length > this.oldQishu.length) {
                difference = e.find(item => this.oldQishu.indexOf(item) === -1)
                // 选中 “全部”时
                if (difference === 0) {
                    this.qishu = this.qishuOptions.map(item => item.value)
                } else {
                    // 如果选中项数为 除了 “全部” 外的所有
                    if (e.length === this.qishuOptions.length - 1) {
                        this.qishu = this.qishuOptions.map(item => item.value)
                    }
                }
            } else {
                // 取消
                difference = this.oldQishu.find(item => e.indexOf(item) === -1)
                if (difference === 0) {
                    this.qishu = []
                } else {
                    // 如果取消之前是全部选中，则取消选中 “全部”
                    if (this.oldQishu.length === this.qishuOptions.length) {
                        this.qishu.splice(0, 1)
                    }
                }
            }
            this.oldQishu = this._.clone(this.qishu)
            this.selectStageShowColumn()
        },
        // 输入后计划金额
        onCalcAmount (row) {
            this.$emit('isMonitorTaxRate')
            if(!row.structureId) return
            if(row.structureId && this.mapTableData[row.parentId].unit === '总额') {
                console.log('')
            }else{
                row.amountEndChange = (row.changeType !== -1 && row.changeType !== -2) ?  row.quantityEndChange * row.unitPriceEndChange : 0
            }

            if((row.changeType !== -1 && row.changeType !== -2)) {
                row.changeType = row.changeType === 1   ? 1 : 2
                row.changeState = row.changeState === 1   ? 1 : 2
            }
            // 向上汇总金额
            this.recurCount({
                parentId: row.parentId,
                rootId: '0',
                listField: 'billId',
                parentField: 'parentId',
                row
            })
        },
        // 递归统计父级
        recurCount ({ parentId, rootId, listField, parentField, row }) {
            // 到根节点
            if (parentId === rootId) {
                return
            }
            const parent = this.mapTableData[parentId]
            // 统计所有同级
            let countSibling = parent.children.reduce((prev, item) => {
                item.amountEndChange = item.amountEndChange ? parseFloat(item.amountEndChange) : item.amountEndChange
                return prev + ((item.changeType !== -1 && item.changeType !== -2) ? item.amountEndChange : 0)
            }, 0)
            // 赋值汇总数据给父级
            countSibling = typeof (countSibling) === 'string' ? parseFloat(countSibling) : countSibling
            parent.amountEndChange = parseFloat(countSibling.toFixed(2))
            if(parent.changeType !== -1 && parent.changeType !== -2) {
                parent.changeType = parent.changeType === 1 ? 1 : 2
                parent.changeState = parent.changeState === 1 ? 1 : 2
            }
            // 未到根节点则继续遍历父节点
            return this.recurCount({
                parentId: parent[parentField],
                rootId,
                listField,
                parentField,
                row,
            })
        },
        // 递归统计父级
        recurCountInit ({ parentId, rootId, listField, parentField, row }) {
            // 到根节点
            if (parentId === rootId) {
                return
            }
            const parent = this.mapTableData[parentId]
            // 统计所有同级
            let countSibling = parent.children.reduce((prev, item) => {
                item.amountEndChange = item.amountEndChange ? parseFloat(item.amountEndChange) : item.amountEndChange
                return prev + ((item.changeType !== -1 && item.changeType !== -2) ? item.amountEndChange : 0)
            }, 0)
            // 赋值汇总数据给父级
            countSibling = typeof (countSibling) === 'string' ? parseFloat(countSibling) : countSibling
            parent.amountEndChange = parseFloat(countSibling.toFixed(2))
            // 未到根节点则继续遍历父节点
            return this.recurCount({
                parentId: parent[parentField],
                rootId,
                listField,
                parentField,
                row,
            })
        },
        async uidBuilder (params) {
            let temp = ''
            await uidBuilder(params).then(res => {
                console.log(res, 'res')
                temp = res.length === 1 ? res[0] : res
            })
            return temp
        },
        onSearch () {

        }
    }
}
</script>
<style lang='scss' scoped>
    ::v-deep .hide-icon{
        .el-table__expand-icon{
            display: none;
        }
    }
    ::v-deep.el-table__row{
        .cell{
            display: flex;
            align-items: center;
        }
        td:nth-child(5),td:nth-child(6),td:nth-child(7){
            .cell{
                display: block;
            }
        }
        td:nth-child(8),td:nth-child(9),td:nth-child(10){
            .cell{
                justify-content: flex-end;
            }
        }
    }
    ::v-deep .el-popover__reference-wrapper{
        display: flex;
        height: 100%;
    }
    .select_box{display: flex; align-items: center;
        .label{margin: 0 0 0 10px; font-weight: bold;font-size: 13px;}
        ::v-deep .el-radio-group{display: flex;
            .el-radio{display: flex; align-items: center; margin-right: 10px;}
        }
    }
    ::v-deep.handle{display: flex; align-items: center; cursor: pointer; font-size: 0;}
    .e-tree-table {
        ::v-deep.el-table__fixed{background: #fff;}
    }
</style>
